package com.tyx.chargingpile.job;


import com.tyx.chargingpile.cache.SocketChannelMap;
import com.tyx.chargingpile.service.impl.ChargingPileTimeDwn;
import com.tyx.chargingpile.util.DateUtils;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 前置定时下发校时
 */
@Component
@Configuration
@EnableScheduling
public class TimeDownJob {

    private final static Logger LOGGER = LoggerFactory.getLogger(TimeDownJob.class);

    @Autowired
    private ChargingPileTimeDwn chargingPileTimeDwn;

    @Scheduled(cron = "0 0 0 * * ? ")
    public void configureTasks(){
        LOGGER.info("前置下发校时开始.....");
        Map<String,String> map = SocketChannelMap.getChannelMapperMap();
        if(map != null) {
            map.forEach((k, v) -> {
                ChannelHandlerContext channelHandlerContext = (ChannelHandlerContext) SocketChannelMap.getChanneLContext(v);
                timeDown(channelHandlerContext,k);
            });
        }
        LOGGER.info("前置下发校时结束.....");
    }

    @Async
    public void timeDown(ChannelHandlerContext channelHandlerContext,String pileNum){
        Map<String,String> dwn = new HashMap<>();
        dwn.put("time", DateUtils.format(DateUtils.now(),DateUtils.yyMMddHHmmss));
        LOGGER.info("桩编号" + pileNum + "下发校时");
        try {
            chargingPileTimeDwn.execute(channelHandlerContext,dwn);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.info("桩编号" + pileNum + "下发校时失败");
        }
    }
}
